package com.fucius.study.leetcode;

public class ReverseKGroup {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode tempHead = head;

        ListNode newTail = null;
        ListNode newHead = null;
        ListNode tempTail = tempHead;

        int index = 1;
        while(head!=null){
            //遍历原链表
            head = head.next;
            tempTail = head;
            index++;

            if (index%k==0) {
                //剩余链表
                head = head.next;
                index++;
                tempTail.next=null;

                //新链表
                while(tempHead!=null){
                    tempTail = tempHead;
                    tempHead = tempHead.next;
                }

                //反转后的新链表

                //把反转后的链表装到原链表上
                if (newTail!=null){
                    newTail.next = tempHead;
                }
                newTail = tempTail;
                tempTail = head;

            }
        }
        return newHead;
    }


    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next = new ListNode(3);
        head.next = new ListNode(4);
        head.next = new ListNode(5);
        head.next = new ListNode(6);
        head.next = new ListNode(7);
        head.next = new ListNode(8);
        head.next = new ListNode(9);
        head.next = new ListNode(10);
        head.next = new ListNode(11);
        int k = 2;
        head = new ReverseKGroup().reverseKGroup(head, k);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
